//
//  BCWalletExchangeController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2019/1/17.
//  Copyright © 2019 guoshikeji. All rights reserved.
//

#import "BCWalletExchangeController.h"
//
#import "BCEnabledBottomButton.h"
#import "BCWalletExchangeContentView.h"

//纪录
#import "BCWalletDetailController.h"
//
#import "BCWalletPassSetController.h"
//
#import "BCWalletExchangePayPassController.h"
//
#import "BCURLController.h"

//request
#import "UserWalletExchangeRequest.h"
#import "BCUserSafeCenterRequest.h"

//
#import "BCWalletExchangeDataModel.h"

@interface BCWalletExchangeController () <BCWalletPassSetControllerDelegate,BCWalletExchangeContentViewDelegate>

@property (nonatomic, strong) BCWalletExchangeContentView *exchangeContentView;


@property (nonatomic, strong) BCEnabledBottomButton *exchangeButton;

#pragma mark - data
/**
 *BCWalletExchangeDataModel
 */
@property (nonatomic, strong) BCWalletExchangeDataModel *dataModel;

@end

@implementation BCWalletExchangeController

- (BCWalletExchangeDataModel *)dataModel {
    if (!_dataModel) {
        _dataModel = [BCWalletExchangeDataModel new];
    }
    return _dataModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self requestExchangeDataInit:true refresh:false];
}

- (void)setupSubviews {
    //
    self.exchangeButton = [BCEnabledBottomButton new];
//    [self.exchangeButton.displayButton setTitle:self.title forState:UIControlStateNormal];
    self.exchangeButton.backgroundColor = [UIColor darkMainColor];
    self.exchangeButton.enabledBackgorundColor = [UIColor darkMainColor];
    self.exchangeButton.unEnabledBackgorundColor = [UIColor qmui_colorWithHexString:@"#C1C0C9"];
    [self.view addSubview:self.exchangeButton];
    [self.exchangeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo([BCBottomButton defaultHeight]);
    }];
    self.exchangeButton.alpha = 0;
    [self.exchangeButton addTarget:self action:@selector(exchangeButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    self.exchangeContentView = [BCWalletExchangeContentView new];
    self.exchangeContentView.alpha = 0;
    self.exchangeContentView.delegate = self;
    self.exchangeContentView.fromController = self.navigationController;
    [self.view addSubview:self.exchangeContentView];
    [self.exchangeContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.exchangeButton.mas_top);
    }];
    [self.view layoutIfNeeded];
}

/**
 兑换纪录
 */
- (void)didClickedNaviRightButton {
    [self toExchangeRecordAction];
}
#pragma mark - exchangeButtonDidClickedAction
- (void)exchangeButtonDidClickedAction {
    NSString *exchangeAmount = self.exchangeContentView.exchangeAmount;
    if (!exchangeAmount.length) {
        return;
    }
    
    NSString *avalaibel = self.dataModel.fromCurrency.money;
    //
    if (exchangeAmount.floatValue>avalaibel.floatValue) {
        NSString *do_amount = self.dataModel.exchangeData.flow.do_amount;
        NSString *avString = [NSString stringWithFormat:@"%@%@",avalaibel,self.dataModel.fromCurrency.acronyms];
        NSString *info = [do_amount stringByReplacingOccurrencesOfString:@"{}" withString:avString];
        [QMUITips showInfo:info inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:info]];
        return;
    }
    [self checkUserSetPayPass];
}

#pragma mark - BCWalletExchangeContentViewDelegate
- (void)walletExchangeContentViewExplainAction {
    NSString *explain_url = self.dataModel.exchangeData.flow.agreement.url;
    if (explain_url.length) {
        BCURLController *explain = [BCURLController new];
        explain.urlString = explain_url;
        [self.navigationController pushViewController:explain animated:true];
    }
}


#pragma mark - request
- (void)requestExchangeDataInit:(BOOL)init refresh:(BOOL)refresh {
    if (init) {
        [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
    }
    UserWalletExchangeRequest *request = [UserWalletExchangeRequest new];
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.view bc_hiddenLoading];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        UserWalletExchangeResponse *resp = result;
        [wself handleResponseData:resp.data init:init refresh:refresh];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
//            NSString *errorMsg = error.domain;
//            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
            if (init) {
                [wself.view bc_showWithInsets:UIEdgeInsetsMake(CGRectGetHeight(wself.customNaviBar.frame), 0, 0, 0) error:error needRefresh:true refreshTitle:nil target:self refreshAction:@selector(requestInitFailedAction)];
            }
        }
    }];
    [request requestServer];
}
- (void)requestInitFailedAction {
    [self.view bc_hiddenError];
    [self requestExchangeDataInit:true refresh:false];
}

- (void)handleResponseData:(UserWalletExchangeData *)respData init:(BOOL)init refresh:(BOOL)refresh {
    if (respData) {
        //title
        self.title = respData.flow.title;
        if (respData.menus) {
            [self.customNaviBar.rightButton setTitle:respData.flow.exchange_log forState:UIControlStateNormal];
        }
        //exchange
        self.exchangeButton.alpha = 1;
        [self.exchangeButton.displayButton setTitle:respData.flow.exchange_record forState:UIControlStateNormal];
        //
        if (respData.data.count<=1) {
            self.exchangeButton.enabled = false;
        }
        
        self.exchangeContentView.alpha = 1;
        self.dataModel.exchangeData = respData;
        self.exchangeContentView.dataModel = self.dataModel;
    }
}



#pragma mark - actions
/**
 去兑换纪录
 */
- (void)toExchangeRecordAction {
    BCWalletDetailController *details = [BCWalletDetailController new];
    details.title = self.dataModel.exchangeData.flow.exchange_log;
    details.menuItem = self.dataModel.exchangeData.menus;
    details.singleDetail = true;
    [self.navigationController pushViewController:details animated:true];
}


#pragma mark - check
/**
 检查是否设置了支付密码
 */
- (void)checkUserSetPayPass {
    BCUserSafeCenterData *safeData = [BCUserManager sharedUser].safeCenterData;
    if (safeData) {
        //去支付
        [self toPayAction:safeData];
    }else {
        [self requestPayPassSetAction];
    }
}
#pragma mark - other request
- (void)requestPayPassSetAction {
    //请求一次是否设置了支付密码
    WEAK_SELF
    [self.exchangeButton bc_showActivityIndicatorBackgroundColor:self.exchangeButton.backgroundColor insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        [wself.exchangeButton bc_hiddenActivityIndicator];
        if (error) {
            if (wself.view) {
                NSString *errMsg = error.domain;
                [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            }
        }else {
            //去支付
            [wself toPayAction:resp.data];
        }
    }];
}
#pragma mark - toPayAction
- (void)toPayAction:(BCUserSafeCenterData *)safeData {
    //判断是否开启支付密码
    if (safeData.data.has_pay_pass) {
        //弹出支付界面
        [self toInputPayPassAction];
    }else {
        WEAK_SELF
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:safeData.flow.no_paypass.mess message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.cancel style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *setting = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.sub style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wself toSetPayPassAction];
        }];
        [alertVC addAction:cancel];
        [alertVC addAction:setting];
        [self presentViewController:alertVC animated:true completion:nil];
    }
}
/**
 去设置支付密码
 */
- (void)toSetPayPassAction {
    //需要处理数据
    BCUserSafeCenterData *data = [BCUserManager sharedUser].safeCenterData;
    NSString *account;
    BCaptchaSendType sendType = BCaptchaSendTypePhone;
    if (data.data.has_email) {
        account = data.data.email;
        sendType = BCaptchaSendTypeEmail;
    }else if (data.data.has_phone) {
        account = data.data.phone;
        sendType = BCaptchaSendTypePhone;
    }
    if (!account.length) {
        return;
    }
    BCWalletPassSetController *pass = [BCWalletPassSetController new];
    pass.account = account;
    pass.sendType = sendType;
    pass.delegate = self;
    [self.navigationController pushViewController:pass animated:true];
}
#pragma mark - BCWalletPassSetControllerDelegate
- (void)walletPassSetSuccessAction {
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        
    }];
}

/**
 输入支付密码 兑换
 */
- (void)toInputPayPassAction {
    self.dataModel.amount = self.exchangeContentView.exchangeAmount;
    WEAK_SELF
    [BCWalletExchangePayPassController showFromController:self.navigationController dataModel:self.dataModel complete:^(UserWalletExchangeOprationResponse * _Nonnull resp) {
        if (resp&&wself.view) {
            [wself exchangedSuccess:resp];
        }
    }];
}
- (void)exchangedSuccess:(UserWalletExchangeOprationResponse *)resp {
    NSString *msg = resp.msg;
    [QMUITips showSucceed:msg inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
    //刷新和清空UI
    [self.exchangeContentView clearInput];
    //
    [self requestExchangeDataInit:false refresh:true];
}

@end
